<?php
use yii\helpers\Url;
use app_supplier\assets\SuppAssets;
SuppAssets::addArrayCss($this, ['@web/admin/view/stylesheet/stylesheet.css','@web/admin/view/stylesheet/form.css','@web/admin/view/stylesheet/button.css','@web/admin/view/stylesheet/basemod.css','@web/admin/view/stylesheet/jquery.webui-popover.min.css','@web/admin/view/javascript/jquery/ui/themes/flick/jquery-ui-1.8.16.custom.css','@web/javascript/layer/layer.css']);
SuppAssets::addArrayScript($this, ['@web/admin/view/javascript/jquery/jquery-1.7.1.min.js','@web/admin/view/javascript/jquery/ui/jquery-ui-1.8.9.custom.min.js','@web/admin/view/javascript/jquery/ui/external/jquery.bgiframe-2.1.2.js','@web/javascript/layer/layer.js','@web/javascript/main.js']);
?>
<!--<base href="--><?php //echo $this->thisBase(); ?><!--" />-->
<style type="text/css">
    a {
        text-decoration: none;
        text-decoration-color: -moz-use-text-color;
        text-decoration-line: none;
        text-decoration-style: solid;
    }
</style>
<script>
    var amount = 0;
    var isReturn = "<?=$isReturn?>";
    var issetPrint = parseInt("<?=$issetPrint?>");
</script>
<script>
    var app = {
        data: {amount: amount, cash: amount, bank: 0, othres: 0, discount: 0, receivable: 0, remark: ''},
        init: function () {
//            var is_back = "<?//=$is_back?>";
            if (isReturn != '') {
                $(".isReturn").html("实收金额：");
            }
            //非调拨
            <?php if(!$is_allocat): ?>
            var backData = parent.app.submit();
            if (backData.operation == 5 || backData.operation == 6) {
                $("#receivable").attr("disabled", "disabled");
            }
            var total_price = parseFloat(backData.total.toFixed(2));
            <?php else: ?>
            var total_price = parseFloat(<?=$total_price?>);
            <?php endif; ?>
            $("#total-price").html(total_price);
            $("#pay_by_cash").attr("value", total_price);
            $("#order_pay").html(total_price);
            amount = total_price;
            app.data.amount = total_price;
            app.data.cash = total_price;
        },
        priceChange: function (e, k) {
            if (!(/^\d+(\.{0,1}\d+){0,1}$/.test($(e).val()))) {
                layer.alert("请输入正确的金额格式");
                $(e).val(0);
                this.data[k] = parseFloat($(e).val());
                this.data.amount = this.data.cash + this.data.bank + this.data.othres + this.data.discount + this.data.receivable;
                $("#order_pay").html(this.data.amount.toFixed(2));
                return false;
            }
            this.data[k] = parseFloat($(e).val());
            this.data.amount = this.data.cash + this.data.bank + this.data.othres + this.data.discount + this.data.receivable;
            $("#order_pay").html(this.data.amount.toFixed(2));
        },
        submit: function () {
            //非调拨
            <?php if(!$is_allocat): ?>
            //获取采购或者退购的配件信息
            var purchaseData = parent.app.submit();
            if (!purchaseData) {
                layer.alert("采购列表没有数据");
                return false;
            }
            <?php endif; ?>
            this.data.remark = $("#deposit_notes").val();
            if (amount != this.data.amount) {
                if (isReturn != '') {
                    layer.alert("应收与实收不等，不能结算！");
                } else {
                    layer.alert("应付与实付不等，不能结算！");
                }

                return false;
            }
            //获取结算单数据
            var purchase_no = $("#purchase_no").val();

            var pay_by_cash = $("#pay_by_cash").val();
            pay_by_cash = parseFloat(pay_by_cash.length == 0 ? 0 : pay_by_cash);

            var pay_by_bank = $("#pay_by_bank").val();
            pay_by_bank = parseFloat(pay_by_bank.length == 0 ? 0 : pay_by_bank);
            var bank_id = $("#pay_by_bank").attr('data-id');
            bank_id = pay_by_bank>0?bank_id:0;

            var pay_by_others = $("#pay_by_others").val();
            pay_by_others = parseFloat(pay_by_others.length == 0 ? 0 : pay_by_others);

            var others_id = $("#pay_by_others").attr('data-id');
            others_id = pay_by_others>0?others_id:0;

            var pay_by_discount = $("#pay_by_discount").val();
            pay_by_discount = parseFloat(pay_by_discount.length == 0 ? 0 : pay_by_discount);

            var receivable = $("#receivable").val();
            receivable = parseFloat(receivable.length == 0 ? 0 : receivable);
            var presale_notes = $("#presale_notes").val()
//            var isReturn = "<?//=$isReturn ?>";
            var dealer_id = 0;//"<?//=$dealer_id ?>";
            var store_id = "<?=$dealer_id; ?>";  //获取材料的调拨店
            var header_number = "<?=$header_number ?>";
            var clearingData = {
                amount: amount,
                pay_by_cash: pay_by_cash,
                pay_by_bank: pay_by_bank,
                pay_by_bank_id:bank_id,
                pay_by_others: pay_by_others,
                pay_by_others_id:others_id,
                pay_by_discount: pay_by_discount,
                receivable: receivable,
                presale_notes: presale_notes,
                header_number: header_number,
                dealer_id: dealer_id
            };
            //console.log(JSON.stringify(clearingData));
            var postData = { isReturn: isReturn, clearingData: JSON.stringify(clearingData)};
            //是否是调拨
            var is_allocat = "<?=$is_allocat; ?>";
            if(is_allocat == 0){    //非调拨
                if (isReturn == '') {
                    var url = '<?=Url::to(['inventory/clearingwarehouse'])?>';
                    var txt = "入库单";
                }
                else {
                    var url = '<?=Url::to(['inventory/clearingOutWareHouse'])?>';
                    var txt = "出库单";
                }
                $.post(url, postData, function (d) {
                    if (d.flag) {
                        if (issetPrint) {
                            //非调拨
                            <?php if(!$is_allocat): ?>
                            parent.app.print(header_number,txt);
                            <?php endif; ?>
                        } else {
                            layer.alert('结算成功！', function () {
                                //非调拨
                                <?php if(!$is_allocat): ?>
                                parent.location.reload();
                                <?php endif; ?>
                            });
                        }
                    } else
                        layer.alert(d.msg, { closeBtn:false,time:1000 });
                }, "json");
            }else if(is_allocat == 1){
                //出库
                $.post("<?=Url::to(['inventory/clearingOutWareHouse'])?>", postData, function (d) {
                    if (d.flag) {
                        if (issetPrint) {
                            parent.app.print(header_number,'出库单');
                        } else {
                            layer.alert('结算成功！',{ closeBtn:false,time:1000 },function(){
                                parent.location.reload();
                            });
                        }
                    } else
                        layer.alert(d.msg,{ closeBtn:false,time:1000 });
                }, "json");
            }else if(is_allocat == 2){
                //入库
                clearingData.store_id = store_id;
                postData = { clearingData: JSON.stringify(clearingData)};
                $.post("<?=Url::to(['inventory/clearingEnterWareHouse'])?>", postData, function (d) {
                    if (d.flag) {
                        if (issetPrint) {
                            parent.app.print(header_number,'入库单');
                        } else {
                            layer.alert('结算成功！',{ closeBtn:false,time:1000 },function(){
                                parent.location.reload();
                            });
                        }
                    } else
                        layer.alert(d.msg,{ closeBtn:false,time:1000 });
                }, "json");
            }
        }
    }

    $(function () {
        app.init();
    })
</script>

<div style="padding: 20px;">
    <label>待结算金额：￥<span id="total-price"><?=isset($price) ? $price : $total_price; ?></span></label>

    <table id="settlement" bordercolor='grey' border='1'
           style="border-collapse: collapse; width:100%; font-size:14px; margin-top:10px;">
        <tr>
            <th style="width:10%;"><label class="isReturn">实付金额：</label></th>
            <td style="padding-top:10px; padding-bottom:10px;">
                <label style="margin-left:10px;">现<i style=" visibility:hidden;">传</i>金：</label>
                <input type="text" id="pay_by_cash" value="0" onfocus="if(value==0){value=''}" onblur="if(value==''){value=0}" style="width:60px; text-align:right; " onkeyup="app.priceChange(this,'cash');">

                <?php if(count($payaccount['bank'])>0):?>
                    <?php $curBank=$payaccount['bank'][0];?>
                    <?php foreach($payaccount['bank'] as $item):?>
                        <?php if($item['is_default']=='1'){ $curBank=$item; }?>
                    <?php endforeach;?>
                    <label style="margin-left:50px" onclick="bank.select(this,'#bank-list')" title="<?=$curBank['account_number']?>" ><?=$curBank['account_type']?><!--(**<?=substr($curBank['account_number'],-4)?>)-->：</label>
                    <input type="text" data-id="<?=$curBank['id']?>" id="pay_by_bank" value="0" onfocus="if(value==0){value=''}" onblur="if(value==''){value=0}" style="width:60px; text-align:right; " onkeyup="app.priceChange(this,'bank');">
                <?php else:?>
                    <label style="margin-left:50px;">银行卡：</label>
                    <input type="text" data-id="0" id="pay_by_bank" value="0" onfocus="if(value==0){value=''}" onblur="if(value==''){value=0}" style="width:60px; text-align:right; " onkeyup="app.priceChange(this,'bank');">
                <?php endif;?>

                <label style="margin-left:50px"onclick="bank.select(this,'#else-list')">其<i style=" visibility:hidden;">传</i>它：</label>
                <input type="text"  data-id="0" id="pay_by_others" value="0" onfocus="if(value==0){value=''}" onblur="if(value==''){value=0}" style="width:60px; text-align:right; " onkeyup="app.priceChange(this,'othres');">
                <label style="margin-left:50px; color:red;">优<i style=" visibility:hidden;">传</i>惠：</label>
                <input type="text" id="pay_by_discount" value="0" onfocus="if(value==0){value=''}" onblur="if(value==''){value=0}" style="width:60px; text-align:right; " onkeyup="app.priceChange(this,'discount');">
                </br>

                <style>
                    .popup-pay{ width: 220px;position: fixed;display: none;top: 63px;left:286px;z-index: 2000;background-color: #fff;border:1px solid #b5b5b5; }
                    .popup-pay i{ border-left: 12px solid transparent;border-right: 12px solid transparent;border-bottom:10px solid #b5b5b5;position: absolute;left:10px;top: -11px; }
                    .popup-pay > div{ height: 128px;overflow: hidden;overflow-y: auto; }
                    .popup-pay > div ul{ padding: 0px;border:0px;margin: 0px; }
                    .popup-pay > div ul  li{ width: 100%;height: 32px;list-style-type: none; padding: 0px;border:0px;margin: 0px; }
                    .popup-pay > div ul  li div{ line-height: 32px;padding: 0px 10px;font-size:13px;cursor: pointer; }
                    .popup-pay > div ul  li:hover{ background-color: #ebebeb; }
                    .popup-pay > div ul  li.cur{ background-color: #0000ff;color:#fff; }
                </style>
                <div class="popup-pay" id="bank-list">
                    <i></i>
                    <div>
                        <ul>
                            <?php foreach($payaccount['bank'] as $item):?>
                                <li data-id="<?=$item['id']?>" title="<?=$item['account_number']?>"><div><?=$item['account_type']?></div></li>
                            <?php endforeach;?>
                        </ul>
                    </div>
                </div>
                <div class="popup-pay" id="else-list">
                    <i></i>
                    <div>
                        <ul>
                            <?php foreach($payaccount['wechat'] as $item):?>
                                <li data-id="<?=$item['id']?>" title="<?=$item['account_number']?>"><div><?=$item['account_type']?></div></li>
                            <?php endforeach;?>
                            <?php foreach($payaccount['alipay'] as $item):?>
                                <li data-id="<?=$item['id']?>" title="<?=$item['account_number']?>"><div><?=$item['account_type']?></div></li>
                            <?php endforeach;?>
                            <li data-id="0" title=""><div>其&nbsp;&nbsp;它</div></li>
                        </ul>
                    </div>
                </div>
                <script>
                    var bank={
                        obj:'',
                        timeout:0,
                        init:function(){

                            $(".popup-pay div ul li").click(function(){
                                var theEvent = window.event || arguments.callee.caller.arguments[0];
                                theEvent.stopPropagation();
                                $(this).parents(".popup-pay").find('li').removeClass('cur');
                                $(this).addClass("cur");
                                $(bank.obj).html($(this).text()+"：");
                                $(bank.obj).attr("title",$(this).attr('title'));
                                $(this).parents(".popup-pay").hide();
                                $(bank.obj).next().attr("data-id",$(this).attr("data-id"));
                            });
                            $("body").click(function(){
                                $(".popup-pay").hide();
                            });
                        },
                        select:function(e,_obj){
                            $(".popup-pay").hide();
                            var theEvent = window.event || arguments.callee.caller.arguments[0];
                            theEvent.stopPropagation();
                            var eOffset=$(e).offset();
                            var eH=$(e).height()+10;
                            $(_obj).css({ "left":eOffset.left+"px","top":(eOffset.top+eH)+"px" });
                            $(_obj).show();
                            this.obj=e;
                        }
                    }
                    bank.init();
                </script>

            </td>
        </tr>
        <?php if($dealer_id == ''): ?>
        <tr style="display: none">
            <?php else: ?>
        <tr>
            <?php endif; ?>
            <th>挂账金额：</th>
            <td style="padding-top:10px; padding-bottom:10px;">
                <input type="text" id="receivable" value="0" style="width:80px; text-align:right; margin-left:10px;"
                       onblur="app.priceChange(this,'receivable');">
            </td>
        </tr>
        <tr>
            <th>备注信息：</th>
            <td style="padding-top:10px; padding-bottom:10px;">
                <input type="text" id="presale_notes" style="width:78%; margin-left:10px;" placeholder="备注信息：">
            </td>
        </tr>
        <tr>
            <td colspan=2 style="padding-top:10px; padding-bottom:10px;">
                <label class="isReturn" style="margin-left:70px;font-weight: bolder">实付金额：</label>
                ￥<span id="order_pay" style="width:40px; display:inline-block;">0</span>

                <a style="margin-left: 50px" href="javascript:void(0);" onclick="app.submit()" id="btn-submit"
                   class="button">结算</a>
            </td>
        </tr>
    </table>
</div>

<script type="text/javascript" src="../admin/view/javascript/jquery/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var has_card = <?php if (!empty($cardInfo)) echo 1; else echo 0; ?>;
        if (has_card) {
            $("#tr_card").show();
            useCard();
        }

        var has_coupon = <?php if (isset($coupons[0]['coupon_id'])) echo 1; else echo 0; ?>;
        if (has_coupon)
            $("#settlement tr:eq(2)").show();

        var has_promotions = <?php if (isset($promotions[0]['id'])) echo 1; else echo 0; ?>;
        if (has_promotions)
            $("#settlement tr:eq(3)").show();
    });

    function onSelectCoupon(discount, coupon_id, type)
    {
        if (!$("#check_coupon_" + coupon_id).attr("checked")) {
            $("#discount_" + coupon_id).val(0);
            $("#coupon_amount_" + coupon_id).text(discount);
        }
        else {
            if (type == 'T') {
                $(".service_times").each(function () {
                    if ($(this).attr('checked')) {
                        layer.alert('是否与会员卡重复抵扣？');
                    }
                });
            }
        }

        onAmountChange();
    }

    function onDiscountChange(coupon_type, coupon_id)
    {
        var val = $("#discount_" + coupon_id).val();

        if (val.search("^-?\\d+$") != 0) {
            layer.alert("请输入一个整数的抵扣值!");
            return;
        }

        if ($("#check_coupon_" + coupon_id).attr("checked")) {
            useCoupon(coupon_type, coupon_id, val);
            onAmountChange();
        }
    }

    function onSelectCardService(str)
    {
        //layer.alert(str);
    }

    function setSettlement(obj)
    {
        if (obj.getAttribute('class').indexOf('notequal') > 0) {
            layer.alert('应收与实收不等，不能结算！');
            return false;
        }

        if (obj.getAttribute('class').indexOf('disabled') > 0) {
            layer.alert('已提交结算！',{ closeBtn:false,time:1000 });
            return false;    //avoid repeat submit
        }

        var pay_by_card = $("#pay_by_card").val();
        pay_by_card = parseFloat(pay_by_card.length == 0 ? 0 : pay_by_card);

        var card_amount = parseFloat($("#card_amount").text());
        if (pay_by_card > card_amount) {
            layer.alert('会员卡余额不足，不能结算！',{ closeBtn:false,time:1000 });
            $(obj).removeClass("disabled");
            return false;
        }

//	var order_id = <?//=$info['id']; ?>;

        var payInfo = new Array();
        payInfo[0] = pay_by_card;

        var pay_by_cash = $("#pay_by_cash").val();
        payInfo[1] = parseFloat(pay_by_cash.length == 0 ? 0 : pay_by_cash);

        var pay_by_bank = $("#pay_by_bank").val();
        payInfo[2] = parseFloat(pay_by_bank.length == 0 ? 0 : pay_by_bank);

        var pay_by_others = $("#pay_by_others").val();
        payInfo[3] = parseFloat(pay_by_others.length == 0 ? 0 : pay_by_others);

        var pay_by_discount = $("#pay_by_discount").val();
        payInfo[4] = parseFloat(pay_by_discount.length == 0 ? 0 : pay_by_discount);

        var receivable = $("#receivable").val();
        payInfo[5] = parseFloat(receivable.length == 0 ? 0 : receivable);

        var presale = $("#presale").val();
        payInfo[6] = parseFloat(presale.length == 0 ? 0 : presale);

        var presale_notes = $("#presale_notes").val()
        payInfo[7] = presale_notes;

        //payInfo[3] = $("#deposit_notes").val();

        var cardInfo = new Array();
        var has_card = <?php if (!empty($cardInfo)) echo 1; else echo 0;?>;
        if (has_card) {
            cardInfo[0] = $("#card_number").val();
            cardInfo[1] = $("#card_password").val();
            cardInfo[2] = $("#card_description").val();
            cardInfo[3] = $("#sms_send").attr("checked");

            var service_times = '';

            $(".service_times").each(function () {
                if ($(this).attr('checked')) {
                    service_times += $(this).val();
                    service_times += '-';
                }
            });

            if (service_times.substr(-1) == "-")
                service_times = service_times.substring(0, service_times.length - 1)

            cardInfo[4] = service_times;
        }

        var couponInfo = new Array();
        var flag = 0;
        $(".check_coupon").each(function () {
            if ($(this).attr("checked")) {
                coupon_id = $(this).val().split('_')[0];
                discount = $("#discount_" + coupon_id).val();
                amount = Number($("#coupon_amount_" + coupon_id).text().replace(/,/, ''));
                if (discount.search("^-?\\d+$") != 0 || discount <= 0) {
                    layer.alert('请填写正确的优惠券抵扣数量',{ closeBtn:false,time:1000 });
                    flag = 1;
                    $(obj).removeClass("disabled");
                    return;
                }

                var arr = [coupon_id, discount, amount];
                couponInfo.push(arr);
            }
        });

        if (flag) {
            $(obj).removeClass("disabled");
            return;
        }

        var promotionsInfo = new Array();
        $(".check_promotions").each(function () {
            if ($(this).attr("checked")) {
                promotionsInfo.push($(this).val());
            }
        });

        $(obj).addClass("disabled");

        $.post("<?=Url::to(['order/setSettlement'])?>", {order_id:order_id, 'payInfo':payInfo.toString(), 'cardInfo':cardInfo.toString(), 'couponInfo':couponInfo.toString(), 'promotionsInfo':promotionsInfo.toString()}, function (data, textStatus) {

            if (data.hasOwnProperty('flag')) {
                if (!data.flag) {
                    layer.alert(data.msg,{ closeBtn:false,time:1000 });
                    $(obj).removeClass("disabled");
                    return;
                }
            }

            if (data.result == '') {
                layer.alert('结算成功！', function () {
                    if (data.str_pos_page != '')
                        posPrint(data.str_pos_page);

                    parent.location.reload();
                });
                //console.log(data.str_pos_page)
            }
            else {
                layer.alert(data.result,{ closeBtn:false,time:1000 });
                $(obj).removeClass("disabled");
            }
        }, "json");
    }

    function useCoupon(coupon_type, coupon_id, val)
    {
        $.post('<?=Url::to(['order/useCoupon'])?>',{'coupon_id':coupon_id, 'coupon_val':val}, function (data, textStatus) {
            if (data.result != '')
                layer.alert(data.result,{ closeBtn:false,time:1000 });
            else
                $("#coupon_amount_" + coupon_id).text(data.new_discount);
        }, "json");
    }

    function useCard()
    {
        var card_number = $("#card_number").val();
        var order_id = "<?=$info['id']?>";

        $("#card_name").text('');
        $("#card_amount").text('');
        $("#card_description").text('');
        $("#amount_discounts").text('');
        $("#order_pay").val('');
        $("#tbl_service_times tr").remove();

        $.post('<?=Url::to(['order/useCard'])?>',{'card_number':card_number, 'order_id':order_id}, function (data, textStatus) {
            if (data.result == 'card_stopped') {
                layer.alert(card_number + '卡已停用！');
                return;
            }

            if (data.result != '')
                layer.alert(data.result);

            $("#card_name").text(data.amount.name);
            $("#card_amount").text(data.amount.amount);
            $("#card_description").text(data.amount.description);
            $("#pay_by_discount").val(data.amount.discounts);
            $("#pay_by_card").val(data.amount.payable);
            $("#order_pay").val(Math.round(data.amount.order_pay));

            if (data.times.length) {
                for (var i = 0; i < data.times.length; i++) {
                    var org_times = parseInt(data.times[i].times);
                    var new_times = org_times - 1;

                    var table = $("#tbl_service_times");
                    var row = $("<tr></tr>");
                    var td = $("<td style='width:160px; padding:10px;'><label><INPUT TYPE='checkbox' class='service_times' value='" + data.times[i].service_id + "_" + data.times[i].service_name + "_" + org_times + "' checked style='margin-top:2px;' onclick='javascript:onSelectCardService(this.value);'>" +
                        "<span style='font-size:14px; margin-left:5px;'>" + data.times[i].service_name + "</span></label></td>" +
                        "<td style='width:80px; text-align:right; font-size:14px;'>剩余次数：</td>" +
                        "<td style='width:40px;'><span style='font-size:14px;'>" + org_times + "</span></td>" +
                        "<td style='width:80px; text-align:right; font-size:14px;'>抵用后：</td>" +
                        "<td style='width:40px;'><span style='font-size:14px;'>" + new_times + "</span></td>");
                    row.append(td);
                    table.append(row);
                }
            }

            onAmountChange();
        }, "json");
    }

    function onAmountChange()
    {
        var order_pay = 0;

        var pay_by_cash = $("#pay_by_cash").val();
        order_pay += parseFloat(pay_by_cash.length == 0 ? 0 : pay_by_cash);

        var has_card = <?php if (!empty($cardInfo)) echo 1; else echo 0; ?>;
        if (has_card) {
            var pay_by_card = $("#pay_by_card").val();
            order_pay += parseFloat(pay_by_card.length == 0 ? 0 : pay_by_card);
        }

        var pay_by_bank = $("#pay_by_bank").val();
        order_pay += parseFloat(pay_by_bank.length == 0 ? 0 : pay_by_bank);

        var pay_by_others = $("#pay_by_others").val();
        order_pay += parseFloat(pay_by_others.length == 0 ? 0 : pay_by_others);

        var pay_by_discount = $("#pay_by_discount").val();
        order_pay += parseFloat(pay_by_discount.length == 0 ? 0 : pay_by_discount);

        var receivable = $("#receivable").val();
        order_pay += parseFloat(receivable.length == 0 ? 0 : receivable);

        $(".check_coupon").each(function () {
            if ($(this).attr("checked")) {
                coupon_id = $(this).val().split('_')[0];
                coupon_type = $(this).val().split('_')[1];
                if (coupon_type == 'F') {
                    discount = $("#discount_" + coupon_id).val();
                    order_pay += parseFloat(discount);
                }
            }
        });

        var order_price = "<?=$info['order_price']?>";
        if (order_price != order_pay)
            $("#btn-submit").addClass("notequal");
        else
            $("#btn-submit").removeClass("notequal");

        var real_pay = 0;
        var presale = $("#presale").val();
        real_pay = order_pay + parseFloat(presale.length == 0 ? 0 : presale);

        $("#order_pay").text(order_pay);
        $("#real_pay").text(real_pay);
    }
</script>

<script type="text/javascript">
    function posPrint(str)
    {
        openwindow = window.open("<?=Url::to(['order/settlementPos?number='.$info['order_number']]) ?>" + str);
        openwindow.onload = function () {
            openwindow.print();
        }
    }

</script>

